<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import userStore from '../store/userStore.js'
import { testScanSimulation, setScannerReady } from '../api.js'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const operator = ref('')
    const project_name = ref('')
    const count = ref('')
    const software_version = ref('')
    const loading = ref(false)
    const error = ref('')
    const readyNotification = ref('') // 就绪状态提示消息
    const errorNotification = ref('')

    // WebSocket相关变量
    let websocket = null
    let reconnectInterval = 1000 // 初始重连间隔（1秒）
    const maxReconnectInterval = 30000 // 最大重连间隔（30秒）
    const backend = 'localhost:8005' // 后端地址

    const handleLogin = () => {
      if (!operator.value.trim()) {
        error.value = '请输入操作人员'
        return
      }
      
      if (!project_name.value.trim()) {
        error.value = '请输入项目名称'
        return
      }
      
      if (!count.value.trim()) {
        error.value = '请输入列数'
        return
      }
      
      if (!software_version.value.trim()) {
        error.value = '请输入软件版本'
        return
      }
      
      loading.value = true
      error.value = ''
      
      // 模拟登录过程
      setTimeout(() => {
        loading.value = false
        
        // 保存用户信息到全局状态，保留已有的trace_barcode
        userStore.setUser({
          operator: operator.value.trim(),
          project_name: project_name.value.trim(),
          count: count.value.trim(),
          software_version: software_version.value.trim(),
          trace_barcode: userStore.get('trace_barcode') // 保留已通过WebSocket获取的trace_barcode
        })
        
        // 跳转到PLC显示界面
        router.push('/plc')
      }, 1000)
    }

    const handleKeyPress = (event) => {
      if (event.key === 'Enter') {
        handleLogin()
      }
    }

    // 扫码模拟测试函数
    const testScanSimulationHandler = async () => {
      console.log('扫码模拟按钮被点击')
      try {
        const response = await testScanSimulation()
        console.log('扫码模拟请求成功:', response)
      } catch (error) {
        console.error('扫码模拟请求失败:', error)
      }
    }

    const openProjectConfig = () => {
      userStore.set('openProjectList', true)
    }
    const errorProjectCode = ref('')
    const openConfigFromError = () => {
      if (errorProjectCode.value) {
        userStore.set('prefill_project_code', errorProjectCode.value)
      }
      userStore.set('openProjectList', true)
      errorNotification.value = ''
      errorProjectCode.value = ''
    }

    // WebSocket连接管理
    const initWebSocket = () => {
      console.log('Login页面开始初始化WebSocket连接...')
      
      // 关闭已存在的连接
      if (websocket) {
        console.log('关闭现有WebSocket连接')
        websocket.close()
      }
      
      // 创建新的WebSocket连接
      console.log(`创建新的WebSocket连接: ws://${backend}/ws/scanner`)
      websocket = new WebSocket(`ws://${backend}/ws/scanner`)
      
      // 设置事件处理器
      setupWebSocketHandlers()
    }

    // 设置WebSocket事件处理器
    const setupWebSocketHandlers = () => {
      // 连接建立时的回调
      websocket.onopen = () => {
        console.log('Login页面WebSocket连接已成功建立')
        reconnectInterval = 1000 // 重置重连间隔
      }
      
      // 接收消息的回调
      websocket.onmessage = (event) => {
        try {
          console.log('Login页面收到WebSocket消息:', event.data)
          const message = JSON.parse(event.data)
          
          // 处理field_update类型的消息
          if (message.type === 'field_update') {
            console.log(`Login页面更新字段: ${message.field_name} = ${message.field_value}`)
            
            // 动态更新项目名称字段
            if (message.field_name === 'project_name') {
              project_name.value = message.field_value
              userStore.set('project_name', message.field_value)
              console.log('Login页面项目名称已更新:', message.field_value)
            }
            
            // 处理追溯条码更新（虽然Login页面不显示，但可以记录到userStore）
            if (message.field_name === 'trace_barcode') {
              userStore.set('trace_barcode', message.field_value)
              console.log('Login页面追溯条码已更新到userStore:', message.field_value)
            }
            }
            if (message.type === 'project_not_configured') {
              errorNotification.value = `项目编号未配置: ${message.project_code}`
              errorProjectCode.value = message.project_code
            }
        } catch (err) {
          console.error('Login页面WebSocket消息解析错误:', err)
        }
      }
      
      // 连接关闭时的回调
      websocket.onclose = () => {
        console.log('Login页面WebSocket连接已关闭')
        // 自动重连
        setTimeout(() => {
          console.log(`Login页面${reconnectInterval}ms后尝试重连WebSocket...`)
          initWebSocket()
          // 增加重连间隔，但不超过最大值
          reconnectInterval = Math.min(reconnectInterval * 2, maxReconnectInterval)
        }, reconnectInterval)
      }
      
      // 连接错误时的回调
      websocket.onerror = (error) => {
        console.error('Login页面WebSocket连接错误:', error)
        // 主动关闭以触发 onclose 重连
        if (websocket) {
          websocket.close()
        }
      }
    }

    // 通知后端前端已就绪
    const notifyBackendReady = async () => {
      try {
        readyNotification.value = '正在初始化扫码枪监控...'
        // 更新图标为加载状态
        setTimeout(() => {
          const icon = document.querySelector('.notification-icon')
          if (icon) {
            icon.classList.add('loading')
          }
        }, 100)
        
        const response = await setScannerReady()
        
        if (response.success) {
          readyNotification.value = '扫码枪监控已就绪，可以开始扫码。'
          console.log('后端扫码枪监控已就绪:', response)
          
          // 更新图标为成功状态
          setTimeout(() => {
            const icon = document.querySelector('.notification-icon')
            if (icon) {
              icon.textContent = '✅'
              icon.classList.remove('loading')
            }
          }, 100)
          
          // 3秒后隐藏提示消息
          setTimeout(() => {
            readyNotification.value = ''
          }, 3000)
        } else {
          readyNotification.value = '扫码枪监控初始化失败'
          console.error('设置扫码枪就绪状态失败:', response)
          
          // 更新图标为错误状态
          setTimeout(() => {
            const icon = document.querySelector('.notification-icon')
            if (icon) {
              icon.textContent = '❌'
              icon.classList.remove('loading')
            }
          }, 100)
        }
      } catch (error) {
        readyNotification.value = '扫码枪监控初始化失败'
        console.error('通知后端就绪失败:', error)
        
        // 更新图标为错误状态
        setTimeout(() => {
          const icon = document.querySelector('.notification-icon')
          if (icon) {
            icon.textContent = '❌'
            icon.classList.remove('loading')
          }
        }, 100)
        
        // 3秒后隐藏错误消息
        setTimeout(() => {
          readyNotification.value = ''
        }, 3000)
      }
    }

    // 组件挂载时初始化WebSocket
    onMounted(() => {
      initWebSocket()
      // 通知后端前端已就绪
      notifyBackendReady()
    })

    // 组件卸载时清理WebSocket连接
    onUnmounted(() => {
      if (websocket) {
        console.log('Login页面组件卸载，关闭WebSocket连接')
        websocket.close()
        websocket = null
      }
    })

    return {
      operator,
      project_name,
      count,
      software_version,
      loading,
      error,
      readyNotification,
      errorNotification,
      errorProjectCode,
      handleLogin,
      handleKeyPress,
      testScanSimulationHandler,
      openProjectConfig,
      openConfigFromError
    }
  }
}
</script>

<template>
  <div class="login-app">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-container">
        <div class="logo-section">
          <img src="../../assets/icon/raw_logo.jpg" alt="Wabtec Logo" class="logo" />
        </div>
        <h2 class="system-title">
          产品生产记录系统
        </h2>
        <div class="spacer"></div>
        <button @click="openProjectConfig" class="project-list-btn" type="button">项目配置</button>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="main-content">
      <div class="login-container">
        <div class="login-card">
          <div class="login-header">
            <div class="login-icon">👤</div>
            <h3 class="login-title">用户登录</h3>
          </div>
          
          <div class="login-form">
            <div class="form-group">
              <label for="operator" class="form-label">操作人员</label>
              <input
                id="operator"
                v-model="operator"
                type="text"
                class="form-input"
                placeholder="请输入操作人员"
                @keypress="handleKeyPress"
                :disabled="loading"
              />
            </div>
            
            <div class="form-group">
              <label for="project_name" class="form-label">项目名称</label>
              <input
                id="project_name"
                v-model="project_name"
                type="text"
                class="form-input"
                placeholder="请输入项目名称"
                @keypress="handleKeyPress"
                :disabled="loading"
              />
            </div>
            
            <div class="form-group">
              <label for="count" class="form-label">列数</label>
              <input
                id="count"
                v-model="count"
                type="text"
                class="form-input"
                placeholder="请输入列数"
                @keypress="handleKeyPress"
                :disabled="loading"
              />
            </div>
            
            <div class="form-group">
              <label for="software_version" class="form-label">软件版本</label>
              <input
                id="software_version"
                v-model="software_version"
                type="text"
                class="form-input"
                placeholder="请输入软件版本"
                @keypress="handleKeyPress"
                :disabled="loading"
              />
            </div>
            
            <div v-if="error" class="error-message">
              <span class="error-icon">⚠️</span>
              {{ error }}
            </div>
            
            <button
              @click="handleLogin"
              class="login-button"
              :disabled="loading || !operator.trim() || !project_name.trim() || !count.trim() || !software_version.trim()"
            >
              <div v-if="loading" class="loading-spinner"></div>
              <span v-if="!loading">登录系统</span>
              <span v-else>正在登录...</span>
            </button>
          </div>
          
          <div class="login-footer">
            <p class="footer-text">
              <span class="footer-icon">🔒</span>
              打开界面时存在的内容是扫码枪之前扫描到的二维码的值，可以重新扫码进行覆盖
            </p>
          </div>
        </div>
      </div>
    </main>
    
    <!-- 临时测试按钮 - 扫码模拟 -->
    <button @click="testScanSimulationHandler" class="test-scan-button">扫码模拟</button>
    
    <!-- 扫码枪就绪状态弹窗提示 -->
    <div v-if="readyNotification" class="notification-toast">
      <div class="toast-content">
        <div class="toast-icon">
          <span class="notification-icon">🔄</span>
        </div>
        <div class="toast-message">
          <span class="toast-text">{{ readyNotification }}</span>
        </div>
        <div class="toast-close" @click="readyNotification = ''">
          <span>×</span>
        </div>
      </div>
      <div class="toast-progress"></div>
    </div>
    <div v-if="errorNotification" class="notification-toast" style="border-color:#f5c6cb;">
      <div class="toast-content">
        <div class="toast-icon" style="background: linear-gradient(135deg, #dc3545, #b71c1c);">
          <span class="notification-icon">❌</span>
        </div>
        <div class="toast-message">
          <span class="toast-text" style="color:#b71c1c;">{{ errorNotification }}</span>
        </div>
        <button class="add-project-btn" style="margin-left:8px;" @click="openConfigFromError">去配置</button>
        <div class="toast-close" @click="errorNotification = ''">
          <span>×</span>
        </div>
      </div>
      <div class="toast-progress" style="background: linear-gradient(90deg, #dc3545, #b71c1c);"></div>
    </div>
  </div>
</template>

<style scoped>
:root {
  --primary-color: #2c5aa0;
  --secondary-color: #4a90e2;
  --success-color: #28a745;
  --danger-color: #dc3545;
  --warning-color: #ffc107;
  --info-color: #17a2b8;
  --light-color: #f8f9fa;
  --dark-color: #343a40;
  --border-color: #dee2e6;
  --shadow-color: rgba(0, 0, 0, 0.1);
}

.login-app {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #c9ccd6;
}

/* 顶部导航栏 */
.header {
  background: white;
  color: #333;
  padding: 0 30px 0 0;
  height: 70px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  height: 100%;
  padding: 0 20px;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logo {
  height: 71px;
  width: auto;
  object-fit: contain;
  margin: 10px 0;
}

.system-title {
  flex: 1;
  text-align: center;
  font-size: 28px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.spacer {
  width: 60px; /* 占位符，保持标题居中 */
}

.project-list-btn {
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.3s ease;
}
.project-list-btn:hover { background-color: #1976d2; }
.project-list-btn:active { background-color: #0d47a1; }

.add-project-btn {
  background-color: var(--primary-color);
  color: #ffffff;
  border: none;
  padding: 8px 14px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.2s ease, transform 0.1s ease;
  box-shadow: 0 2px 4px rgba(13, 71, 161, 0.2);
}
.add-project-btn:hover { background-color: #1976d2; }
.add-project-btn:active { transform: translateY(1px); }

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.login-container {
  width: 100%;
  max-width: 450px;
  margin: 0 auto;
}

.login-card {
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
  border-radius: 20px;
  box-shadow: 
    0 20px 60px rgba(0, 0, 0, 0.15),
    0 8px 25px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.8);
  overflow: hidden;
  position: relative;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, var(--primary-color), var(--secondary-color), var(--primary-color));
}

.login-header {
  text-align: center;
  padding: 20px 20px 20px 20px;
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
}

.login-icon {
  font-size: 20px;
  margin-bottom: 5px;
  opacity: 0.8;
}

.login-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 0px 0;
}

.login-form {
  padding: 0px 40px 40px 40px;
}

.form-group {
  margin-bottom: 25px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #495057;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  padding: 15px 16px;
  border: 2px solid #e9ecef;
  border-radius: 10px;
  font-size: 12px;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
}

.form-input:focus {
  outline: none;
  border-color: var(--secondary-color);
  box-shadow: 
    inset 0 2px 4px rgba(0, 0, 0, 0.05),
    0 0 0 3px rgba(74, 144, 226, 0.15);
  transform: translateY(-1px);
}

.form-input:disabled {
  background: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.form-input::placeholder {
  color: #adb5bd;
  font-style: italic;
}

.error-message {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--danger-color);
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 20px;
  padding: 10px 15px;
  background: linear-gradient(135deg, #fff5f5, #ffeaea);
  border: 1px solid #f5c6cb;
  border-radius: 8px;
  border-left: 4px solid var(--danger-color);
}

.error-icon {
  font-size: 16px;
}

/* 扫码枪就绪状态弹窗样式 */
.notification-toast {
  position: fixed;
  top: 20px;
  right: 20px;
  min-width: 320px;
  max-width: 400px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  border: 1px solid #e2e8f0;
  overflow: hidden;
  z-index: 9999;
  animation: slideInRight 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.toast-content {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  gap: 12px;
}

.toast-icon {
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  border-radius: 50%;
}

.notification-icon {
  font-size: 16px;
  color: white;
  transition: all 0.3s ease;
}

.notification-icon.loading {
  animation: spin 1.5s linear infinite;
}

.toast-message {
  flex: 1;
  min-width: 0;
}

.toast-text {
  color: #374151;
  font-size: 14px;
  font-weight: 500;
  line-height: 1.4;
  word-wrap: break-word;
}

.toast-close {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  transition: background-color 0.2s ease;
}

.toast-close:hover {
  background-color: #f3f4f6;
}

.toast-close span {
  color: #9ca3af;
  font-size: 18px;
  font-weight: 500;
  line-height: 1;
}

.toast-progress {
  height: 3px;
  background: linear-gradient(90deg, #3b82f6, #06b6d4);
  animation: progressBar 3s ease-in-out;
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(100%);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes progressBar {
  from {
    width: 0%;
  }
  to {
    width: 100%;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.login-button {
  width: 100%;
  padding: 15px 20px;
  background: linear-gradient(135deg, var(--secondary-color), var(--primary-color));
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(74, 144, 226, 0.3);
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.login-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s ease;
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(74, 144, 226, 0.4);
}

.login-button:hover:not(:disabled)::before {
  left: 100%;
}

.login-button:active:not(:disabled) {
  transform: translateY(0);
}

.login-button:disabled {
  background: linear-gradient(135deg, #6c757d, #5a6268);
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 2px 8px rgba(108, 117, 125, 0.2);
}

.loading-spinner {
  width: 18px;
  height: 18px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.login-footer {
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  padding: 20px 40px;
  border-top: 1px solid #e9ecef;
}

.footer-text {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 12px;
  color: #6c757d;
  margin: 0;
  font-weight: 500;
}

.footer-icon {
  font-size: 14px;
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 20px 15px;
  }
  
  .login-card {
    border-radius: 15px;
  }
  
  .login-header {
    padding: 30px 30px 15px 30px;
  }
  
  .login-form {
    padding: 15px 30px 30px 30px;
  }
  
  .login-footer {
    padding: 15px 30px;
  }
  
  .login-title {
    font-size: 20px;
  }
  
  .system-title {
    font-size: 22px;
  }
}

@media (max-width: 480px) {
  .login-header {
    padding: 25px 20px 10px 20px;
  }
  
  .login-form {
    padding: 10px 20px 25px 20px;
  }
  
  .login-footer {
    padding: 15px 20px;
  }
  
  .form-input {
    padding: 12px 14px;
    font-size: 14px;
  }
  
  .login-button {
    padding: 12px 16px;
    font-size: 14px;
  }
}

/* 临时测试按钮样式 - 扫码模拟 */
.test-scan-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 12px 20px;
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
  z-index: 1000;
}

.test-scan-button:hover {
  background: linear-gradient(135deg, #ee5a24, #ff6b6b);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(255, 107, 107, 0.4);
}

.test-scan-button:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}
</style>